import {getStoreDetail} from "@src/api/mall/store";
import {getShelfGoods, getStoreGoodsBySelf, goodsQuery, getMemberInfo, getGoodDetail} from '@mall/api/good'
import {storeBindingsBehavior} from "mobx-miniprogram-bindings";
import base from "@src/store/base";
import mall from "@src/store/mall";
import {addGoodsToCart} from "@mall/api/shopCart";
import {getDistance} from "@src/common/utils";
import router from "@src/router";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: base,
    fields: ['businessName', 'businessLogo', 'navBarHeight', 'themeTitleColor', 'themeColor'],
  }, {
    store: mall,
    fields: {
      userLocation: 'userLocation',
      curLocation: 'curLocation',
      defaultStoreId: 'storeId'
    },
    actions: ['initLocation']
  }],
  properties: {},
  data: {
    activeCategoryIndex: 0,
    activeSubIndex: 0,
    scrollTop: 0,
    deliveryType: 'LOCAL',
    storeId: null,
    distance: null,
    triggered: false,
    login: false,
    showSkuDialog: false,
    hiddenToast: true,
    canDelivery: true,
    selectSkuObj: null,
    navHeight: 80,
    errorCode: 0,
    errorMsg: 0,
    pageNum: 1,
    pageSize: 10,
    categoryList: [],
    subCategoryList: [],
  },
  observers: {
    'userLocation, store': function (userLocation, store) {
      if (userLocation && store) {
        let distance = getDistance(userLocation.latitude, userLocation.longitude, store.latitude, store.longitude)
        this.setData({distance: distance})
      } else {
        this.setData({distance: null})
      }
    }
  },
  methods: {
    onLoad(options) {
      let {storeId, deliveryType, goodsSerial} = options;
      if (!deliveryType) {
        deliveryType = 'LOCAL';
      }
      this.setData({storeId: storeId, deliveryType: deliveryType, goodsSerial: goodsSerial})
      const eventChannel = this.getOpenerEventChannel()
      if (eventChannel && eventChannel.on) {
        eventChannel.on('addCart', (data) => {
          this.addCart(data)
        })
      }
    },
    onLogin() {
      this.setData({login: true})
      this.initLocation();
      this.fetchData();
      if (this.data.goodsSerial) {
        this.fetchEnterGoods(this.data.goodsSerial)
      }
    },
    fetchEnterGoods(goodsSerial) {
      let params = {
        goodsSerial: goodsSerial,
        storeId: this.data.storeId,
        pageNum: 1,
        pageSize: 1
      }
      goodsQuery(params).then(res => {
        this.setData({curGoods: res.data.list[0]})
      })
    },
    fetchData() {
      getStoreDetail({storeId: this.data.storeId}).then(res => {
        this.setData({store: res.data})
      })
      getShelfGoods('LOCAL').then(res => {
        let categoryList = res.data;
        let subCategoryList = []
        let shelfId = null;
        if (categoryList.length > 0) {
          subCategoryList = categoryList[0].shelfList
        }
        if (subCategoryList.length > 0) {
          shelfId = subCategoryList[0].shelfId
        }
        this.setData({categoryList, subCategoryList, shelfId, pageNum: 0});
        this.fetchGoodsList();
      })
    },

    fetchGoodsList() {
      let {pageSize, shelfId, storeId, pageNum} = this.data
      if (shelfId == null) {
        this.setData({goodsList: []})
        return;
      }
      let params = {pageNum: pageNum + 1, pageSize: pageSize, shelfId: shelfId}
      getStoreGoodsBySelf(storeId, params).then(res => {
        if (this.data.pageNum !== pageNum ||
            this.data.shelfId !== shelfId ||
            this.data.storeId !== storeId) {
          // 数据已经被改变
          return;
        }
        let goodsList = [];
        if (params.pageNum !== 1) {
          goodsList = this.data.goodsList;
        }
        goodsList = goodsList.concat(res.data.list)
        this.setData({
          goodsList,
          pageNum: res.data.pageNum,
          hasNextPage: res.data.hasNextPage
        })
      })
    },
    handleCategoryClick(e) {
      let activeCategoryIndex = e.currentTarget.dataset.index
      if (this.data.activeCategoryIndex === activeCategoryIndex) {
        return;
      }
      let activeSubIndex = 0;
      let shelfId = null;
      let subCategoryList = this.data.categoryList[activeCategoryIndex].shelfList
      if (subCategoryList.length > 0) {
        activeSubIndex = 0;
        shelfId = subCategoryList[0].shelfId;
      }
      this.setData({
        activeCategoryIndex,
        activeSubIndex,
        subCategoryList,
        shelfId,
        scrollTop: 0,
        hasNextPage: true,
        pageNum: 0
      });
      this.fetchGoodsList();
    },
    handleSubIndex(e) {
      let activeSubIndex = e.currentTarget.dataset.index;
      if (activeSubIndex === this.data.activeSubIndex) {
        return;
      }
      let shelfId = this.data.subCategoryList[activeSubIndex].shelfId
      this.setData({
        activeSubIndex,
        shelfId,
        hasNextPage: true,
        pageNum: 0
      })
      this.fetchGoodsList();
    },
    lastSubCategory() {
      if (this.data.activeSubIndex === 0) {
        return;
      }
      let shelfId = this.data.subCategoryList[this.data.activeSubIndex - 1].shelfId
      this.setData({shelfId: shelfId, activeSubIndex: this.data.activeSubIndex - 1, pageNum: 0})
      this.fetchGoodsList()
    },
    onRefresh() {
      this.setData({triggered: true})
      setTimeout(() => {
        this.setData({triggered: false})
      }, 100)
    },
    handleNextPage() {
      if (this.data.hasNextPage) {
        this.fetchGoodsList();
      }
    },
    handleSearch() {
      console.info("handleSearch")
      router.push({
        name: "mall/store-buy-search",
        params: {storeId: this.data.storeId},
        success: (res) => {
          res.eventChannel.on('refresh', () => {
            console.info("res.eventChannel.emit('refresh', () => {")
            this.selectComponent('#cart').refresh();
          })
        }
      })
    },
    handleStoreChange(e) {
      console.info(e.detail)
      let {deliveryType, store} = e.detail;
      let flag = false;
      if (deliveryType && this.data.deliveryType !== deliveryType) {
        this.setData({deliveryType: deliveryType})
        flag = true;
      }
      if (store && this.data.storeId !== store.storeId) {
        this.setData({storeId: store.storeId})
        flag = true;
      }
      if (flag) {
        this.fetchData();
      }
    },
    handleAdd(e) {
      let goods = e.detail;
      if (goods.skuInfo.skuList.length === 1) {
        let sku = goods.skuInfo.skuList[0];
        let params = {
          storeId: this.data.storeId,
          goodsId: goods.goodId,
          num: 1,
          skuId: sku.skuId,
          type: this.data.deliveryType,
          cartType: 0,
        };
        this.addCart(params);
      } else {
        // 获取商品详情
        let params = {
          goodsSerial: goods.goodsSerial,
          storeId: this.data.storeId
        }
        wx.showLoading({title: "加载中", mask: true});
        getGoodDetail(params).then(res => {
          wx.hideLoading();
          this.setData({goodsObj: res.data})
          setTimeout(res => {
            this.setData({showSkuDialog: true})
          }, 300)
        }).catch(error => {
          wx.hideLoading();
        })
      }
    },
    skuObjFun(detail) {
      this.setData({
        selectSkuObj: detail.detail
      })
    },
    specAddCart(e) {
      let num = 1;
      if (e.detail) {
        num = e.detail
      }
      let sku = this.data.selectSkuObj;
      let params = {
        storeId: this.data.storeId,
        goodsId: this.data.goodsObj.goodsId,
        num: num,
        skuId: sku.skuId,
        type: this.data.deliveryType,
        cartType: 0,
      };
      this.addCart(params);
    },
    addCart(params) {
      params.type = 'LOCAL';
      // 直接添加到购物车
      wx.showLoading({title: "添加中...", mask: true});
      addGoodsToCart(params).then(res => {
        wx.hideLoading();
        this.setData({hiddenToast: false})
        this.selectComponent('#cart').refresh()
        setTimeout(() => {
          this.setData({hiddenToast: true})
        }, 2000)
      }).catch(() => {
        wx.hideLoading();
      })
    },

  }
});
